#include "sendmsg.h"
#include <QJsonDocument>
#include <QJsonObject>

SendMsg::SendMsg(QObject *parent)
    : QObject{parent}
{ }

void SendMsg::ConnectServer(QString ip, unsigned short port)
{
    m_tcp = new QTcpSocket;

    // 连接服务器
    m_tcp->connectToHost(QHostAddress(ip), port);

    // 连接成功的信号处理
    connect(m_tcp, &QTcpSocket::connected, this, &SendMsg::ConnectSuccessful);

    // 连接失败的信号处理
    connect(m_tcp, &QTcpSocket::errorOccurred, this, [=]()/*QAbstractSocket::SocketError socketError*/{
        emit ConnectFail();
    });

    //重新连接的信号处理
    connect(this, &SendMsg::ReconnectServer, this, [=](){
        m_tcp->connectToHost(QHostAddress(ip), port);
    });

    // 断开连接的信号处理
    connect(m_tcp, &QTcpSocket::disconnected, this, [=](){
        m_tcp->close();
        m_tcp->deleteLater();
        emit ConnectOver();
    });

    // 读入数据信号处理
    connect(m_tcp, &QTcpSocket::readyRead, this, [=](){
        QByteArray msg = m_tcp->readAll();
        emit ReceiveMessage(msg);
    });
}

void SendMsg::SendMessage(QJsonDocument doc)
{
    m_tcp->write(doc.toJson());
}
